//
//  BlogContent.swift
//  我的微博
//
//  Created by shmily on 15/8/2.
//  Copyright © 2015年 Stanford-IOS8-Swift-shmilyAshen. All rights reserved.
//

import UIKit
/// 微博内容相关模型
class BlogContent: NSObject {
    /// 微博信息内容
    var text: String?
    /// 微博来源
    var source: String?
    /// 微博创建时间
    var created_at: String?
    /// 微博ID
    var id: Int = 0
    /// 被转发的原微博信息字段，当该微博为转发微博时返回
    var retweeted_status: BlogContent?
    /// 微博作者的用户信息字段
    var user: User?
    
    /// 配图数组(转成 url)
    var pic_urls: [[String: AnyObject]]?{
        didSet {
            if pic_urls?.count == 0 {
                return
            }
            storedUrls = [NSURL]()
            largeStoredUrls = [NSURL]()
            for dict in pic_urls! {
                if let urlString = dict["thumbnail_pic"] as? String {
                    storedUrls?.append(NSURL(string: urlString)!)
                    
                    //大图 url
                    let string = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    largeStoredUrls?.append(NSURL(string: string)!)
                }
            }
        }
    }
    //保存图像的 url(中间变量)
    private var storedUrls: [NSURL]?
    private var largeStoredUrls: [NSURL]?
    /// 图片的 URL 表示
    var picUrls: [NSURL]? {
        return (retweeted_status == nil) ? storedUrls : retweeted_status?.storedUrls
    }
    /// 大图的 URL 显示
    var largePicUrls: [NSURL]? {
        return (retweeted_status == nil) ? largeStoredUrls : retweeted_status?.largeStoredUrls
    }
    
    /// 缓存行高
    var rowHeight: CGFloat?
    
    /// 转发数
    var reposts_count: Int = 0
    /// 评论数
    var comments_count: Int = 0
    /**
    初始化
    */
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    //模型属性比字典多,单独处理
    override func setValue(value: AnyObject?, forKey key: String) {
        //模型嵌套的解决方案
        if key == "user" {
            if let userDict = value as? [String: AnyObject] {
                user = User(dict: userDict)
            }
            return
        }
        //转发微博的信息
        if key == "retweeted_status" {
            if let userDict = value as? [String: AnyObject] {
                retweeted_status = BlogContent(dict: userDict)
            }
            return
        }
        super.setValue(value, forKey: key)
    }
    
    //防止字典过多
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        let keys = ["created_at", "id", "text", "source", "pic_urls","user"]
        
        return "\(dictionaryWithValuesForKeys(keys))"
    }
}
